<!--
 * @Descripttion:
 * @version:
 * @Author: maqq
 * @Date: 2019-08-06 16:08:32
 * @LastEditTime: 2020-10-20 09:50:41
 -->

<script>
/**
 *   使用须知：
 *   该组件使用的是JSX语法，因此所以传参需要注意参数名称
 *   template语法中的参数      table-footer要转换为   tableFooter
 *   其次所有事件比如    @click   需转换为   onClick
 *   所以连字符处转换为 驼峰语法
 *   部分语法糖不兼容 如  v-if之类的，但都有对应的js代码可以执行
 *   所有额外的参数在prop中传入
 *   created by maqq  20190802
 */
export default {
  data () {
    return {
      loading: false,
      tableData: [],
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  props: {
    reqFn: {
      type: Function,
      required: true
    },
    params: {
      type: Object,
      default: () => ({})
    },
    footerMethod: {
      type: Function,
      default: undefined
    },
    props: {
      type: Object,
      default: () => ({})
    },
    pagerProps: {
      type: Object,
      default: () => ({})
    },
    toolbarProps: {
      type: Object,
      default: () => ({})
    },
    on: {
      type: Object,
      default: () => ({})
    },
    pagerOn: {
      type: Object,
      default: () => ({})
    },
    showPage: {
      type: Boolean,
      default: true
    },
    notReq: {
      type: Boolean,
      default: false
    },
    defaultTablePage: {
      type: Object,
      default: () => ({})
    },
    formatField: {
      type: Object
    },
    fieldNames: {
      type: Object
    }
  },
  computed: {
    showFooter () {
      return !!this.footerMethod
    },
    showToolbar () {
      return Object.keys(this.toolbarProps).length > 0
    }
  },
  created () {
    if (!this.notReq) {
      this.initDefaultPage()
      this.fetch()
    }
  },
  methods: {
    initDefaultPage () {
      this.tablePage = {
        ...this.tablePage,
        ...this.defaultTablePage
      }
    },
    fetch () {
      this.loading = true
      console.log(`this.params`, this.params)
      return this.reqFn({
        params: {
          ...this.params,
          pageIndex: this.tablePage.currentPage,
          pageSize: this.tablePage.pageSize
        }
      })
        .then(res => {
          console.log('res-----------------------------', res)
          if (res && res.success) {
            this.tablePage.total = res.result.recordCount || 0
            const data = res.result.result || []
            if (this.formatField && JSON.stringify(this.formatField !== `{}`)) {
              for (const item of data) {
                for (const key in item) {
                  if (this.formatField[key]) {
                    item[key] = this.formatField[key](item[key])
                  }
                }
              }
            }

            if (this.fieldNames) {
              const objKeys = Object.keys(this.fieldNames)
              for (const item of data) {
                for (const key of objKeys) {
                  const isExistKey = Object.keys(item).length && Object.keys(item).includes(key)
                  if (isExistKey) {
                    item[this.fieldNames[key]] = item[key]
                    delete item[key]
                  }
                }
              }
            }
            this.tableData = data
            console.log(`this.tableData`, this.tableData)
            this.$emit('record-update', res.result)
          } else {
            this.$message.error('加载列表失败')
          }
          this.loading = false
        })
        .catch(e => {
          this.loading = false
        })
    },
    handlePageChange ({ currentPage, pageSize }) {
      console.log('翻页')
      const before = Object.assign({}, this.tablePage)
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.$emit('pageChange', this.tablePage, before)
      this.fetch()
    },
    async reload (index = 1) {
      this.tablePage.currentPage = index
      await this.fetch()
    },
    getPageConfig () {
      return {
        pageIndex: this.tablePage.currentPage,
        pageSize: this.tablePage.pageSize
      }
    },
    getPageData () {
      return this.tableData
    }
  },
  render () {
    const {
      loading,
      tablePage,
      tableData,
      showFooter,
      footerMethod,
      handlePageChange,
      props,
      toolbarProps,
      on,
      showPage,
      showToolbar
    } = this
    return (
      <div>
        {
          showToolbar &&
          <vxe-toolbar
            id="myToolBar"
            { ...toolbarProps }
          >
            {Object.keys(this.$slots).map(key => {
              return this.$slots[key]
            })}
          </vxe-toolbar>
        }
        <vxe-table
          border
          show-overflow
          auto-resize
          stripe
          ref='xTable'
          class="vxe-table-antd"
          row-id='_uid'
          loading={this.loading}
          seq-config={{
            startIndex: (tablePage.currentPage - 1) * tablePage.pageSize
          }}
          // checkbox-config={{checkRowKeys: ['2', '3'], highlight: true}}
          data={tableData}
          showFooter={showFooter}
          footerMethod={footerMethod}
          align="center"
          resizable
          {...{
            props: {
              height: '450',
              ...props
            },
            on: on
          }}
        >
          {Object.keys(this.$slots).map(key => {
            return this.$slots[key]
          })}
          <span slot="empty">当前数据为空</span>
        </vxe-table>
        {showPage && <vxe-pager
          loading={loading}
          currentPage={tablePage.currentPage}
          pageSize={tablePage.pageSize}
          total={tablePage.total}
          layouts={['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump', 'Total']}
          {
          ... {
            props: {
              ...this.pagerProps
            },
            on: {
              'page-change': handlePageChange,
              ...this.pagerOn
            }
          }
          }
        ></vxe-pager>}
      </div>
    )
  }
}
</script>
<style lang="scss">
.table-header {
  height: 54px;
  line-height: 54px;
  font-size: 14px;
  font-family: PingFangSC-Medium;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}
.table-row {
  height: 54px;
  line-height: 54px;
  font-size: 14px;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.65);
}
</style>
